<template>
  <div class="goods-selling">
    <h3>出售中商品</h3>

    <!-- 搜索框 -->
    <el-input v-model="searchKeyword" placeholder="输入商品名搜索" style="max-width: 300px; margin-bottom: 15px" />

    <!-- 商品表格 -->
    <el-table :data="filteredProducts" border style="width: 100%">
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="sales" label="销量" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="prev, pager, next" :total="100" />

    <!-- 编辑商品弹窗 -->
    <el-dialog title="编辑商品" v-model="editDialogVisible" width="40%">
      <el-form :model="editingProduct" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="editingProduct.name" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="editingProduct.price" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="editingProduct.stock" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editingProduct.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="出售中" value="出售中" />
            <el-option label="已下架" value="已下架" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const products = ref([
  { id: 1, name: 'iPhone 15', price: 8999, stock: 50, sales: 200, status: '出售中' },
  { id: 2, name: 'Nike 运动鞋', price: 799, stock: 100, sales: 150, status: '出售中' }
])

const searchKeyword = ref('')

// 过滤商品
const filteredProducts = computed(() => {
  if (!searchKeyword.value) return products.value
  return products.value.filter(p => p.name.includes(searchKeyword.value))
})

// 控制弹窗显示
const editDialogVisible = ref(false)
const editingProduct = ref({})

// 打开编辑弹窗
const openEditDialog = (product) => {
  editingProduct.value = { ...product }
  editDialogVisible.value = true
}

// 保存编辑
const saveProduct = () => {
  const index = products.value.findIndex(p => p.id === editingProduct.value.id)
  if (index !== -1) {
    products.value.splice(index, 1, editingProduct.value)
    ElMessage.success('商品信息已更新')
    editDialogVisible.value = false
  }
}
</script>

<style scoped>
.goods-selling {
  padding: 20px;
}
</style>